import logging
import traceback

from django.http import HttpResponseForbidden
from django.utils.deprecation import MiddlewareMixin

from utils.permissions import APIIPRestrictor

logger = logging.getLogger('django.request')

class ServerHeaderMiddleware:
    """
    避免header Server泄露信息
    default header Server: WSGIServer/x.x CPython/3.x.x
    """

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        response['Server'] = 'iHarborS3'
        return response


class CloseCsrfMiddleware(MiddlewareMixin):

    def process_request(self, request):
        request.csrf_processing_done = True  # csrf处理完毕


class AdminIPRestrictMiddleware:
    admin_url = '/admin'

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        if request.path.startswith(self.admin_url):
            try:
                APIIPRestrictor().check_restricted(request=request)
            except Exception as e:
                return HttpResponseForbidden(f'{str(e)}')
        return self.get_response(request)


class DRFRequestLoggingMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):

        response = None
        try:

            # 调用下一个中间件或视图函数
            response = self.get_response(request)
            if response.status_code > 400 and hasattr(response, 'data'):
                logger.error(f'{request.path} --> {response.data}')
        except Exception as e:
            error_message = f"Error occurred at {request.path}: {str(e)}"
            error_traceback = traceback.format_exc()
            logger.error(error_message)
            logger.error("Traceback:\n%s", error_traceback)

        return response
